package com.nbsaas.boot.script.ext.resource;

import com.nbsaas.boot.script.ext.apis.ScriptResource;
import com.nbsaas.boot.script.ext.domain.simple.ScriptSource;

import java.io.File;
import java.net.URL;

/**
 * 类路径脚本源
 */
public class ClasspathScriptSource implements ScriptResource {

    @Override
    public String getPrefix() {
        return "classpath:";
    }

    @Override
    public ScriptSource loadScript(String path) {
        String actual = path.startsWith(getPrefix()) ? path.substring(getPrefix().length()) : path;
        URL resource = getClass().getClassLoader().getResource(actual);
        if (resource == null) {
            throw new IllegalArgumentException("类路径中未找到脚本: " + actual);
        }
        try {
            File file = new File(resource.toURI());
            return new FileScriptSource().loadScript(file.getAbsolutePath());
        } catch (Exception ignored) {
        }
        return null;
    }
}
